import { reactive, ref, watch, ExtractPropTypes } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import ajax from "@/util/request";

/**
 * 
 * @param modelName 
 * @param props props对象，需要使用defineProps创建后传入
 * @param emits emits对象，需要使用defineEmits创建后传入
 * @param formRules 
 * @param insertURL 
 * @returns 
 */
function setupInsert(modelName: string,
    props: Readonly<ExtractPropTypes<any>>,
    emits: any,
    formRules: FormRules,
    insertURL = `/${modelName}/insert`
) {

    let updated = false;

    const myForm = ref<FormInstance>();
    const formData = reactive({});

    const rules = reactive<FormRules>(formRules);

    /**
     * 清空表单
     * @param myForm 表单对象
     */
    function handleClear(myForm: FormInstance) {
        if (myForm) {
            myForm.resetFields();
        }
        updated = false;
    }

    watch(
        () => props.modelValue,
        () => (updated = false)
    );

    /**
     * 关闭组件
     */
    function handleClose() {
        emits("close", updated);
    }

    /**
     * 提交增加
     * @param myForm 表单对象
     */
    function handleInsert(myForm: FormInstance) {
        myForm.validate((valid) => {
            if (!valid) {
                return;
            }
            ajax(insertURL, { ...formData }).then(({ data }) => {
                if (data.status > 0) {
                    alert({ type: "success", message: "增加成功" });

                    myForm.resetFields();

                    updated = true;
                }
            });
        });
    }

    return {
        rules, myForm, formData, handleClear, handleClose, handleInsert
    }
}

export default setupInsert;